import json

from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.paginator import Paginator
from django.db import connection
from django.db.models import Count
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render
from django.utils.decorators import method_decorator
from django.views import View
from django.views.generic import ListView

from hr.forms import ResumeForm
from hr.models import Resume, Job, Delivery


# Create your views here.

def send_sms(request):
    # 从表单中获取到电话号码
    phone = request.GET.get("phone")
    # 电话号码 放入 session 中
    request.session["sms_phone"] = phone

    # 获取验证码
    sms_code = get_sms_code()

    # TODO 通过短信平台发送短信

    # 短信验证码 放入 session 中
    request.session["sms_code"] = sms_code

    return JsonResponse({"code": sms_code})


# 生成验证码
def get_sms_code():
    import random
    check_code = ''
    for i in range(4):
        tep = random.randint(0, 9)
        check_code += str(tep)
    return check_code


def user_login(request):
    if request.method == 'GET':
        # GET请求方式直接渲染登录页
        return render(request, 'login.html')
    elif request.method == 'POST':
        # 获取表单中的数据
        phone = request.POST.get("phone")
        code = request.POST.get("phone_code")

        # 获取session中的数据
        phone_session = request.session["sms_phone"]
        code_session = request.session["sms_code"]

        # 判断表单数据与session数据 是否一致
        if phone == phone_session and code == code_session:
            # 判断用户是否注册(是否首次使用)
            isExist = User.objects.filter(username=phone).exists()
            if not isExist:  # 用户未注册(User表无记录)
                # 注册
                user = User.objects.create_user(username=phone, password=phone)
            else:  # 用户已注册(User表已有记录)
                # 登录
                user = authenticate(username=phone, password=phone)

            # 将用户对象保存到session中, 实现登录动作
            login(request, user)

            # 登录成功
            return render(request, 'joblist.html')
        else:
            # 登录失败
            return render(request, 'login.html', {'error': '手机号码与短信验证码不匹配'})

# 简历视图类
@method_decorator(login_required, name='dispatch')
class ResumeView(View):
    # GET请求
    def get(self, request):
        # 查询当前用户下的简历
        resumes = Resume.objects.filter(user=request.user)

        resume_exist = None
        if resumes.count() > 0:
            resume_exist = resumes.first() # 默认使用第一份简历

        return render(request, 'resume.html', {'resume': resume_exist})

    # POST请求
    def post(self, request):
        # 使用表单数据创建Form对象
        resume_form = ResumeForm(request.POST)

        # 使用Form对象验证表单数据
        if resume_form.is_valid():
            # 表单验证通过
            id = request.POST.get("id")
            if id != '': # 根据表单的id 是否为空 判断 新增或更新 操作
                # 更新操作
                resume_exist = Resume.objects.get(pk=id)
                resume_form = ResumeForm(request.POST, instance=resume_exist)
            resume = resume_form.save(commit=False) # 使用表单数据创建简历对象
            resume.user = request.user # 简历绑定当前用户对象
            resume.save() # 保存简历对象
            return render(request, 'resume.html', {'msg': "简历保存成功", 'resume': resume})

        else:
            # 表单验证未通过
            return render(request, 'resume.html', {'resume': resume_form})


# 查询职位列表
def search_jobs(request):
    job_list = Job.objects.all().order_by('-id')
    paginator = Paginator(job_list, 3) # 使用Django分页器组件实现分页
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    return render(request, 'joblist.html', {'page_obj': page_obj})

# 职位详情
def job_detail(request, pk):
    detail = Job.objects.get(pk=pk)
    return render(request, 'job.html', {'job': detail})

# 呈递简历
# @login_required()
def presented(request, job_id):
    if not request.user.id:
        return JsonResponse({'code': 403, 'msg': '您尚未登录,请登录后再申请!'})

    # 查询当前用户下的简历
    resumes = Resume.objects.filter(user=request.user)

    if resumes.count() > 0:
        resume_exist = resumes.first()  # 默认使用第一份简历
        Delivery.objects.create(job_id=job_id, resume=resume_exist, state='已投递')
        return JsonResponse({'code': 200, 'msg': '简历投递成功'})
    else:
        return JsonResponse({'code': 404, 'msg': '您尚无简历,请填写简历后申请!'})

# 简历投递职位列表
class DeliveryList(ListView):
    template_name = 'delivery.html'
    context_object_name = 'delivery_list'

    def get_queryset(self):
        id = self.kwargs.get('pk')
        return Delivery.objects.filter(resume__user_id=id)

# 职位城市分布数据API
def api_city_json(request):
    # 职位城市分组统计
    data = Job.objects.filter(position_info__isnull=False).values("address").annotate(job_num=Count("address"))
    # QuerySet对象转换为列表对象
    data_list = list(data)
    # 将列表数据转换为json格式后输出给浏览器端
    return HttpResponse(json.dumps(data_list), content_type="application/json")
